<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能巡检车控制台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #333;
        }
        
        .container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            max-width: 900px;
            width: 95%;
            backdrop-filter: blur(10px);
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            color: #2c3e50;
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .header .subtitle {
            color: #7f8c8d;
            font-size: 1.1em;
            margin-bottom: 20px;
        }
        
        .connection-status {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 0.9em;
            margin-bottom: 10px;
        }
        
        .connection-status.connected {
            background: #d5f4e6;
            color: #27ae60;
            border: 1px solid #27ae60;
        }
        
        .connection-status.disconnected {
            background: #fdf2f2;
            color: #e74c3c;
            border: 1px solid #e74c3c;
        }
        
        .status-panel {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            text-align: center;
        }
        
        .status-item {
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .status-item .label {
            font-size: 0.9em;
            color: #6c757d;
            margin-bottom: 5px;
        }
        
        .status-item .value {
            font-size: 1.2em;
            font-weight: bold;
            color: #495057;
        }
        
        .control-section {
            margin-bottom: 30px;
        }
        
        .section-title {
            font-size: 1.5em;
            color: #34495e;
            margin-bottom: 20px;
            text-align: center;
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .speed-control {
            text-align: center;
            margin: 20px 0;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 15px;
        }
        
        .speed-control label {
            display: block;
            margin-bottom: 15px;
            font-weight: bold;
            color: #2c3e50;
            font-size: 1.1em;
        }
        
        .speed-slider {
            width: 80%;
            height: 10px;
            border-radius: 5px;
            background: #ddd;
            outline: none;
            -webkit-appearance: none;
            margin-bottom: 15px;
        }
        
        .speed-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #3498db;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(52, 152, 219, 0.4);
            transition: all 0.3s ease;
        }
        
        .speed-slider::-webkit-slider-thumb:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.6);
        }
        
        .speed-display {
            font-size: 1.3em;
            color: #e74c3c;
            font-weight: bold;
            padding: 10px;
            background: white;
            border-radius: 10px;
            display: inline-block;
            min-width: 120px;
        }
        
        .control-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 15px;
            max-width: 350px;
            margin: 0 auto;
            aspect-ratio: 1;
        }
        
        .control-btn {
            background: linear-gradient(145deg, #3498db, #2980b9);
            border: none;
            border-radius: 15px;
            color: white;
            font-size: 1.1em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
            min-height: 80px;
            position: relative;
            overflow: hidden;
        }
        
        .control-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: all 0.3s ease;
        }
        
        .control-btn:hover::before {
            width: 100%;
            height: 100%;
        }
        
        .control-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(52, 152, 219, 0.4);
        }
        
        .control-btn:active {
            transform: translateY(0);
        }
        
        .control-btn.stop {
            background: linear-gradient(145deg, #e74c3c, #c0392b);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.3);
            grid-column: 2;
            grid-row: 2;
        }
        
        .control-btn.stop:hover {
            box-shadow: 0 8px 25px rgba(231, 76, 60, 0.4);
        }
        
        .control-btn.forward { grid-column: 2; grid-row: 1; }
        .control-btn.backward { grid-column: 2; grid-row: 3; }
        .control-btn.left { grid-column: 1; grid-row: 2; }
        .control-btn.right { grid-column: 3; grid-row: 2; }
        .control-btn.spin-left { grid-column: 1; grid-row: 1; }
        .control-btn.spin-right { grid-column: 3; grid-row: 1; }
        
        .beep-controls {
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 15px;
        }
        
        .beep-btn {
            background: linear-gradient(145deg, #f39c12, #e67e22);
            border: none;
            border-radius: 12px;
            color: white;
            padding: 15px 25px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(243, 156, 18, 0.3);
            font-size: 1em;
        }
        
        .beep-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(243, 156, 18, 0.4);
        }
        
        .message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
            font-weight: bold;
            display: none;
            animation: slideIn 0.3s ease;
        }
        
        .message.success {
            background: #d5edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .message.info {
            background: #cce7ff;
            color: #004085;
            border: 1px solid #b3d9ff;
        }
        
        .keyboard-hints {
            background: #e9ecef;
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            font-size: 0.9em;
            color: #6c757d;
        }
        
        .keyboard-hints h4 {
            margin-bottom: 10px;
            color: #495057;
        }
        
        .keyboard-hints .hint-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
        }
        
        .api-info {
            background: #e8f4f8;
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            font-size: 0.9em;
            color: #0c5460;
        }
        
        .api-info h4 {
            margin-bottom: 10px;
            color: #0c5460;
        }
        
        .api-info input {
            width: 100%;
            padding: 8px;
            border: 1px solid #bee5eb;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 10px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .control-grid {
                max-width: 280px;
            }
            
            .control-btn {
                font-size: 0.9em;
                min-height: 60px;
            }
            
            .beep-controls {
                flex-direction: column;
                align-items: center;
            }
            
            .beep-btn {
                width: 100%;
                max-width: 200px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚗 智能巡检车控制台</h1>
            <div class="subtitle">前后端分离版本</div>
            <div class="connection-status" id="connectionStatus">
                <span id="connectionText">检查连接中...</span>
            </div>
        </div>
        
        <div class="status-panel">
            <div class="status-grid">
                <div class="status-item">
                    <div class="label">机器人状态</div>
                    <div class="value" id="robotStatus">未知</div>
                </div>
                <div class="status-item">
                    <div class="label">当前动作</div>
                    <div class="value" id="currentAction">停止</div>
                </div>
                <div class="status-item">
                    <div class="label">当前速度</div>
                    <div class="value" id="currentSpeed">0%</div>
                </div>
                <div class="status-item">
                    <div class="label">最后命令</div>
                    <div class="value" id="lastCommand">-</div>
                </div>
            </div>
        </div>
        
        <div class="control-section">
            <div class="section-title">
                <span>🎮</span>
                <span>运动控制</span>
            </div>
            
            <div class="speed-control">
                <label for="speedSlider">速度设置</label>
                <input type="range" id="speedSlider" class="speed-slider" min="1" max="100" value="50">
                <div class="speed-display">速度: <span id="speedValue">50</span>%</div>
            </div>
            
            <div class="control-grid">
                <button class="control-btn spin-left" onclick="moveCart(5)">
                    <div>↺<br>左旋</div>
                </button>
                <button class="control-btn forward" onclick="moveCart(1)">
                    <div>↑<br>前进</div>
                </button>
                <button class="control-btn spin-right" onclick="moveCart(6)">
                    <div>↻<br>右旋</div>
                </button>
                <button class="control-btn left" onclick="moveCart(3)">
                    <div>←<br>左转</div>
                </button>
                <button class="control-btn stop" onclick="moveCart(0)">
                    <div>⬛<br>停止</div>
                </button>
                <button class="control-btn right" onclick="moveCart(4)">
                    <div>→<br>右转</div>
                </button>
                <button class="control-btn" style="grid-column: 1; grid-row: 3; opacity: 0; cursor: default;"></button>
                <button class="control-btn backward" onclick="moveCart(2)">
                    <div>↓<br>后退</div>
                </button>
                <button class="control-btn" style="grid-column: 3; grid-row: 3; opacity: 0; cursor: default;"></button>
            </div>
        </div>
        
        <div class="control-section">
            <div class="section-title">
                <span>🔊</span>
                <span>蜂鸣器控制</span>
            </div>
            <div class="beep-controls">
                <button class="beep-btn" onclick="beepCart(200)">短鸣 (200ms)</button>
                <button class="beep-btn" onclick="beepCart(500)">中鸣 (500ms)</button>
                <button class="beep-btn" onclick="beepCart(1000)">长鸣 (1s)</button>
                <button class="beep-btn" onclick="beepCart(2000)">超长鸣 (2s)</button>
            </div>
        </div>
        
        <div class="keyboard-hints">
            <h4>⌨️ 键盘快捷键</h4>
            <div class="hint-grid">
                <div><kbd>↑</kbd> 或 <kbd>W</kbd> - 前进</div>
                <div><kbd>↓</kbd> 或 <kbd>S</kbd> - 后退</div>
                <div><kbd>←</kbd> 或 <kbd>A</kbd> - 左转</div>
                <div><kbd>→</kbd> 或 <kbd>D</kbd> - 右转</div>
                <div><kbd>Q</kbd> - 左旋</div>
                <div><kbd>E</kbd> - 右旋</div>
                <div><kbd>空格</kbd> - 停止</div>
                <div><kbd>B</kbd> - 蜂鸣</div>
            </div>
        </div>
        
        <div class="api-info">
            <h4>🔧 API配置</h4>
            <label for="apiUrl">后端API地址:</label>
            <input type="text" id="apiUrl" placeholder="http://192.168.35.159:5000" value="http://192.168.35.159:5000">
            <button onclick="testConnection()" style="padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">测试连接</button>
        </div>
        
        <div class="message" id="message"></div>
    </div>

    <script>
        // 全局配置
        const CONFIG = {
            DEFAULT_API_URL: 'http://192.168.35.159:5000',
            STATUS_UPDATE_INTERVAL: 3000,
            MESSAGE_DISPLAY_TIME: 3000,
            MAX_RETRY_COUNT: 3
        };

        // 全局状态
        let currentSpeed = 50;
        let apiUrl = CONFIG.DEFAULT_API_URL;
        let statusUpdateTimer = null;
        let isConnected = false;
        let retryCount = 0;

        // DOM元素引用
        const elements = {
            speedSlider: document.getElementById('speedSlider'),
            speedValue: document.getElementById('speedValue'),
            connectionStatus: document.getElementById('connectionStatus'),
            connectionText: document.getElementById('connectionText'),
            robotStatus: document.getElementById('robotStatus'),
            currentAction: document.getElementById('currentAction'),
            currentSpeed: document.getElementById('currentSpeed'),
            lastCommand: document.getElementById('lastCommand'),
            message: document.getElementById('message'),
            apiUrlInput: document.getElementById('apiUrl')
        };

        // API请求封装
        class ApiClient {
            constructor(baseUrl) {
                this.baseUrl = baseUrl;
            }

            async request(endpoint, options = {}) {
                const url = `${this.baseUrl}${endpoint}`;
                const defaultOptions = {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    timeout: 5000
                };

                const config = { ...defaultOptions, ...options };
                
                try {
                    const controller = new AbortController();
                    const timeoutId = setTimeout(() => controller.abort(), config.timeout);
                    
                    const response = await fetch(url, {
                        ...config,
                        signal: controller.signal
                    });
                    
                    clearTimeout(timeoutId);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    return await response.json();
                } catch (error) {
                    if (error.name === 'AbortError') {
                        throw new Error('请求超时');
                    }
                    throw error;
                }
            }

            async get(endpoint) {
                return this.request(endpoint, { method: 'GET' });
            }

            async post(endpoint, data) {
                return this.request(endpoint, {
                    method: 'POST',
                    body: JSON.stringify(data)
                });
            }
        }

        // 创建API客户端实例
        let apiClient = new ApiClient(apiUrl);

        // 工具函数
        function formatTime(isoString) {
            if (!isoString) return '-';
            const date = new Date(isoString);
            return date.toLocaleTimeString('zh-CN', { 
                hour12: false, 
                hour: '2-digit', 
                minute: '2-digit', 
                second: '2-digit' 
            });
        }

        function showMessage(text, type = 'success') {
            elements.message.textContent = text;
            elements.message.className = `message ${type}`;
            elements.message.style.display = 'block';
            
            setTimeout(() => {
                elements.message.style.display = 'none';
            }, CONFIG.MESSAGE_DISPLAY_TIME);
        }

        function updateConnectionStatus(connected) {
            isConnected = connected;
            const status = elements.connectionStatus;
            const text = elements.connectionText;
            
            if (connected) {
                status.className = 'connection-status connected';
                text.textContent = '🟢 已连接';
                retryCount = 0;
            } else {
                status.className = 'connection-status disconnected';
                text.textContent = '🔴 连接断开';
            }
        }

        // 状态更新
        async function updateStatus() {
            try {
                const response = await apiClient.get('/api/status');
                
                if (response.success) {
                    const data = response.data;
                    
                    // 更新状态显示
                    elements.robotStatus.textContent = data.robot_connected ? '🟢 在线' : '🔴 离线';
                    elements.currentAction.textContent = data.state_name;
                    elements.currentSpeed.textContent = `${data.current_speed}%`;
                    elements.lastCommand.textContent = formatTime(data.last_command_time);
                    
                    updateConnectionStatus(true);
                } else {
                    throw new Error(response.message || '获取状态失败');
                }
            } catch (error) {
                console.error('状态更新失败:', error);
                updateConnectionStatus(false);
                
                // 自动重试机制
                if (retryCount < CONFIG.MAX_RETRY_COUNT) {
                    retryCount++;
                    setTimeout(updateStatus, 2000);
                }
            }
        }

        // 测试连接
        async function testConnection() {
            const newApiUrl = elements.apiUrlInput.value.trim();
            if (!newApiUrl) {
                showMessage('请输入API地址', 'error');
                return;
            }

            try {
                apiUrl = newApiUrl;
                apiClient = new ApiClient(apiUrl);
                
                showMessage('正在测试连接...', 'info');
                
                const response = await apiClient.get('/api/health');
                
                if (response.status === 'healthy') {
                    showMessage('连接测试成功!', 'success');
                    updateConnectionStatus(true);
                    updateStatus();
                    startStatusUpdates();
                } else {
                    throw new Error('服务器状态不健康');
                }
            } catch (error) {
                showMessage(`连接测试失败: ${error.message}`, 'error');
                updateConnectionStatus(false);
            }
        }

        // 控制小车运动
        async function moveCart(state) {
            if (!isConnected) {
                showMessage('请先连接到后端服务器', 'error');
                return;
            }

            try {
                const data = { state, speed: currentSpeed };
                const response = await apiClient.post('/api/move', data);
                
                if (response.success) {
                    showMessage(response.message, 'success');
                } else {
                    showMessage(response.message, 'error');
                }
                
                // 立即更新状态
                setTimeout(updateStatus, 100);
                
            } catch (error) {
                showMessage(`控制失败: ${error.message}`, 'error');
                console.error('控制错误:', error);
            }
        }

        // 控制蜂鸣器
        async function beepCart(duration) {
            if (!isConnected) {
                showMessage('请先连接到后端服务器', 'error');
                return;
            }

            try {
                const data = { duration };
                const response = await apiClient.post('/api/beep', data);
                
                if (response.success) {
                    showMessage(response.message, 'success');
                } else {
                    showMessage(response.message, 'error');
                }
                
            } catch (error) {
                showMessage(`蜂鸣器控制失败: ${error.message}`, 'error');
                console.error('蜂鸣器错误:', error);
            }
        }

        // 紧急停止
        async function emergencyStop() {
            try {
                const response = await apiClient.post('/api/stop');
                if (response.success) {
                    showMessage('紧急停止执行成功', 'success');
                } else {
                    showMessage(response.message, 'error');
                }
                setTimeout(updateStatus, 100);
            } catch (error) {
                showMessage(`紧急停止失败: ${error.message}`, 'error');
            }
        }

        // 启动状态更新定时器
        function startStatusUpdates() {
            if (statusUpdateTimer) {
                clearInterval(statusUpdateTimer);
            }
            statusUpdateTimer = setInterval(updateStatus, CONFIG.STATUS_UPDATE_INTERVAL);
        }

        // 停止状态更新定时器
        function stopStatusUpdates() {
            if (statusUpdateTimer) {
                clearInterval(statusUpdateTimer);
                statusUpdateTimer = null;
            }
        }

        // 事件监听器设置
        function setupEventListeners() {
            // 速度滑块
            elements.speedSlider.oninput = function() {
                currentSpeed = parseInt(this.value);
                elements.speedValue.textContent = this.value;
            };

            // API地址输入框
            elements.apiUrlInput.onchange = function() {
                stopStatusUpdates();
                updateConnectionStatus(false);
            };

            // 键盘控制
            document.addEventListener('keydown', function(event) {
                // 防止在输入框中触发
                if (event.target.tagName === 'INPUT') return;
                
                switch(event.key.toLowerCase()) {
                    case 'arrowup':
                    case 'w':
                        moveCart(1); // 前进
                        event.preventDefault();
                        break;
                    case 'arrowdown':
                    case 's':
                        moveCart(2); // 后退
                        event.preventDefault();
                        break;
                    case 'arrowleft':
                    case 'a':
                        moveCart(3); // 左转
                        event.preventDefault();
                        break;
                    case 'arrowright':
                    case 'd':
                        moveCart(4); // 右转
                        event.preventDefault();
                        break;
                    case ' ':
                        moveCart(0); // 停止
                        event.preventDefault();
                        break;
                    case 'q':
                        moveCart(5); // 左旋
                        event.preventDefault();
                        break;
                    case 'e':
                        moveCart(6); // 右旋
                        event.preventDefault();
                        break;
                    case 'b':
                        beepCart(500); // 蜂鸣
                        event.preventDefault();
                        break;
                    case 'escape':
                        emergencyStop(); // 紧急停止
                        event.preventDefault();
                        break;
                }
            });

            // 页面失去焦点时自动停止
            window.addEventListener('beforeunload', function() {
                if (isConnected) {
                    navigator.sendBeacon(`${apiUrl}/api/stop`, JSON.stringify({}));
                }
            });

            // 窗口可见性变化处理
            document.addEventListener('visibilitychange', function() {
                if (document.hidden) {
                    stopStatusUpdates();
                } else if (isConnected) {
                    startStatusUpdates();
                    updateStatus();
                }
            });
        }

        // 初始化应用
        function initApp() {
            setupEventListeners();
            
            // 设置默认API地址
            elements.apiUrlInput.value = CONFIG.DEFAULT_API_URL;
            
            showMessage('前端应用已加载，请配置后端API地址并测试连接', 'info');
            
            // 尝试自动连接
            setTimeout(() => {
                testConnection();
            }, 1000);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initApp);

        // 导出全局函数供HTML调用
        window.moveCart = moveCart;
        window.beepCart = beepCart;
        window.testConnection = testConnection;
    </script>
</body>
</html>